package dream.util;

import com.mysql.cj.jdbc.MysqlDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtils {
    private DBUtils(){
    }
    private static volatile MysqlDataSource mysqlDataSource;
//    private static volatile Connection connection;

    private static MysqlDataSource getMysqlDataSource(){
        if(mysqlDataSource==null) {
            synchronized (DBUtils.class){
                if (mysqlDataSource == null) {
                    mysqlDataSource = new MysqlDataSource();
                    mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/myblog2022?characterEncoding=utf8&useSSL=false");
//                    mysqlDataSource.setURL("jdbc:mysql://101.42.153.174:3306/myblog2022?characterEncoding=utf8&useSSL=true");
                    mysqlDataSource.setUser("root");
                    mysqlDataSource.setPassword("1234");
                }
            }
        }
        return mysqlDataSource;
    }
    //1.get connection

    /**
     * 单例模式的Connection
     * @return
     * @throws SQLException
     */
//    public static Connection getConnection() throws SQLException {
//        if (connection==null){
//            synchronized (DBUtils.class){
//                if(connection==null){
//                    MysqlDataSource dataSource=getMysqlDataSource();
//                    connection= (Connection) dataSource.getConnection();
//                }
//            }
//        }
//        return connection;
//    }

    /**
     * 多例模式的Connection
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        Connection connection= (Connection) getMysqlDataSource().getConnection();
        return connection;

    }

    //2.关闭资源
    public static void close(ResultSet resultSet, PreparedStatement statement, Connection connection) throws SQLException {
        if(resultSet!=null){
            resultSet.close();
        }
        if(statement!=null){
            statement.close();
        }
    }
}

